<template>
  <div class="page-container">
    <header-nav v-if="!isMiniProgram"/>
    <div class="activity-content">
      <media :query="{minWidth: 768}">
        <div class="pc-media">
          <div class="activity-info">
            <h3>{{activityInfo.Theme}}</h3>
            <div>
              <div class="left-info">
                <div class="activity-logo">
                  <img :src="activityInfo.HeadLogo" alt>
                </div>
                <p>时间：{{activityInfo.ThemeTime}}</p>
                <P>地点：{{activityInfo.Adress}}</P>
                <div class="activity-share" v-show="false">
                  <span>分享：</span>
                  <a href="javascript:;" title="朋友圈"></a>
                  <a href="javascript:;" title="微信"></a>
                </div>
              </div>
              <div class="right-info" v-if="ticketList.length>0">
                <div class="ticket-check">
                  <p>选择票种</p>
                  <van-checkbox-group v-model="checkedTicket" @change="ticketCheck" :max="maxCheckedNum">
                    <van-checkbox
                      :name="index"
                      v-for="(item,index) in ticketList"
                      :key="index"                     
                      :disabled="item.RealNum>=item.Num"
                    >
                      <div class="label-left">
                        <h3 class="ticket-name">{{item.TicketName}}</h3>
                      </div>
                      <div class="label-right" v-if="item.RealNum<item.Num">
                        <span class="ticket-price">{{item.Fee|formatPrice}}</span>
                      </div>
                      <div class="label-right" v-else>已售罄</div>
                    </van-checkbox>
                  </van-checkbox-group>
                </div>
                <div class="ticket-discount">
                  <p>使用优惠码</p>
                  <div class="ticket-coupon" @click="showCouponModel">{{couponTitle}}</div>
                </div>
                <van-dialog
                  v-model="couponModelShow"
                  show-cancel-button
                  :before-close="beforeClose"
                  confirmButtonText="兑换"
                  cancelButtonText="不使用优惠码"
                >
                  <div class="coupon-header">
                    <h3>优惠码兑换</h3>
                    <p>温馨提示：请选择好您要兑换的票种，认真核对，优惠码一经兑换，恕不退还，详情请联系主办方或主委会！</p>
                    <van-cell-group :border="false">
                      <van-field v-model.trim="couponCode" placeholder="请输入优惠码" :border="false"></van-field>
                    </van-cell-group>
                  </div>
                </van-dialog>
                <div class="ticket-num">
                  <p>选择数量</p>
                  <van-stepper
                    v-model="TicketNum"
                    disable-input
                    :max="maxBuyNum"
                    @change="TicketNumChange"
                  />
                </div>
                <div class="activity-sign">
                  <div class="ticket-total">
                    <span>合计</span>
                    <span class="total-price">{{totalPrice|formatPrice}}</span>
                  </div>
                  <div class="next-btn">
                    <van-button type="default" :disabled="checkedTicket.length==0" @click="toNextPage">我要报名</van-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="detail-title">
            <div>活动详情</div>
          </div>
          <div class="activity-html" v-html="Conent"></div>
        </div>
      </media>
      <media :query="{maxWidth: 768}">
        <div class="mb-media">
          <div class="activity-html" v-html="Conent"></div>
          <div class="bottom-btn" v-if="ticketList.length>0">
            <van-button type="default" size="large" @click="showSku">
              <span class="left-icon"></span>
              <span class="right-text">我要报名</span>
            </van-button>
          </div>
          <van-popup v-model="popupShow" position="bottom">
            <div class="activity-ticket">
              <div class="popup-close">
                <van-icon @click="closeSku" name="cross"/>
                <p>请选择</p>
              </div>
              <div class="popup-content">
                <div class="ticket-check">
                  <div>选择票种</div>
                  <van-checkbox-group v-model="checkedTicket" @change="ticketCheck" :max="maxCheckedNum">
                    <van-checkbox
                      :name="index"
                      v-for="(item,index) in ticketList"
                      :key="index"
                      :disabled="item.RealNum>=item.Num"
                    >
                      <div class="label-left">
                        <h3 class="ticket-name">{{item.TicketName}}</h3>
                      </div>
                      <div class="label-right" v-if="item.RealNum<item.Num">
                        <span class="ticket-price">{{item.Fee|formatPrice}}</span>
                      </div>
                      <div class="label-right" v-else>已售罄</div>
                    </van-checkbox>
                  </van-checkbox-group>
                </div>
                <div class="ticket-discount">
                  <div>使用优惠码</div>
                  <van-cell :title="couponTitle" is-link @click="showCouponModel"/>
                </div>
                <div class="ticket-num">
                  <div>选择数量</div>
                  <van-stepper
                    v-model="TicketNum"
                    disable-input
                    :max="maxBuyNum"
                    @change="TicketNumChange"
                  />
                </div>
              </div>
              <div class="popup-bottom">
                <div class="ticket-total">
                  <span>合计</span>
                  <span class="total-price">{{totalPrice|formatPrice}}</span>
                </div>
                <div class="next-btn">
                  <van-button type="default" @click="toNextPage">下一步</van-button>
                </div>
              </div>
            </div>
          </van-popup>
          <van-popup v-model="couponModelShow" position="right">
            <div class="coupon-content">
              <div class="coupon-header">
                <h3>优惠码兑换</h3>
                <p>温馨提示：请选择好您要兑换的票种，认真核对，优惠码一经兑换，恕不退还，详情请联系主办方或主委会！</p>
                <van-cell-group :border="false">
                  <van-field v-model.trim="couponCode" placeholder="请输入优惠码" :border="false">
                    <van-button slot="button" type="default" @click="ExchangeCoupon">兑换</van-button>
                  </van-field>
                </van-cell-group>
              </div>
              <div class="coupon-footer">
                <van-button type="default" size="large" @click="unuseCoupon">不使用优惠码</van-button>
              </div>
            </div>
          </van-popup>
        </div>
      </media>
    </div>
    <media :query="{minWidth: 768}">
      <footer-nav/>
    </media>
  </div>
</template>

<script>
import $ from 'jquery';
import Header from '../components/header';
import Footer from '../components/footer';
import Media from 'vue-media';
export default {
  name: 'EntryPage',
  data() {
    return {
      Conent: null,
      popupShow: false,
      couponModelShow: false,
      ticketList: [],
      checkedTicket: [],
      couponTitle: '优惠码兑换',
      couponCode: '',
      TicketNum: 1,
      maxBuyNum: 1,
      totalPrice: 0,
      maxCheckedNum: 0,
      activityInfo: {},
      isMiniProgram: false,
      shareUrl: window.location.href
    };
  },
  components: {
    'header-nav': Header,
    'footer-nav': Footer,
    media: Media
  },
  filters: {
    formatPrice: function(value) {
      return '￥' + value.toFixed(2);
    }
  },
  created() {
    if (this.$route.query.SessionID) {
      // 小程序内
      this.$store.commit('SET_SESSIONID', this.$route.query.SessionID);
      this.isMiniProgram = true;
    }
    if (this.$route.query.OpenID) {
      localStorage.setItem('OpenId', this.$route.query.OpenID);
      this.$store.commit('SET_OPENID', this.$route.query.OpenID);
    }
    if (this.$route.query.WeixinID) {
      localStorage.setItem('OpenId', this.$route.query.WeixinID);
      this.$store.commit('SET_OPENID', this.$route.query.WeixinID);
    }
    this.$store.commit('SET_USERAGENT', window.navigator.userAgent);
    localStorage.setItem('st', this.$route.params.st);
    this.$store.commit('SET_ST', this.$route.params.st);
    if (this.$route.query.userType) {
      this.$store.commit('SET_USERTYPE', this.$route.query.userType);
    }
    var that = this;
    $.ajax({
      type: 'POST',
      url: that.baseUrl + '/api/Activity/Content',
      data: {
        ST: that.$route.params.st,
        UserType:
          that.$route.query.userType || that.$store.state.UserInfo.UserTypeEnum
      },
      success: function(res) {
        that.$store.commit('setBilingual', res.Bilingual);
        that.Conent = res.ActivityConent;
        that.ticketList = res.Tickets;
        console.log(res.IsPlayMultiSelect);
        that.maxCheckedNum = res.IsPlayMultiSelect ? 0 : 1;
        console.log(that.maxCheckedNum);
        that.activityInfo = {
          Theme: res.Theme,
          HeadLogo: res.HeadLogo,
          ThemeTime: res.ThemeTime,
          Address: res.Address
        };
      }
    });
    // $.ajax({
    //   type: 'GET',
    //   url:
    //     that.baseUrl +
    //     '/api/Activity/get?st=' +
    //     that.$route.params.st +
    //     '&userType=' +
    //     that.$store.state.UserInfo.UserTypeEnum,
    //   success: function(res) {
    //     that.activityInfo = res;
    //   }
    // });
    this.getWxShare();
  },
  methods: {
    getWxShare() {
      var that = this;
      $.ajax({
            type: 'POST',
            url: that.baseUrl + '/api/Activity/GetWeixinShare',
            data: {
                ST: that.$route.params.st,
                UserType:
                that.$route.query.userType || that.$store.state.UserInfo.UserTypeEnum,
                URL: window.location.href.split('#')[0]
            },
            success: (res) => {
                document.title = res.Theme;
                that.wxShare(res, that.shareUrl);
            }
        });
    },
    showSku() {
      this.popupShow = true;
    },
    closeSku() {
      this.popupShow = false;
    },
    showCouponModel() {
      if (this.checkedTicket.length < 2) {
        this.couponModelShow = true;
      } else {
        this.$toast('优惠码只能抵扣一张门票哦');
      }
    },
    toNextPage() {
      if (this.checkedTicket.length < 1) {
        this.$toast('请先选择票种');
      } else {
        let TicketId = [];
        let TicketInfo = [];
        this.checkedTicket.forEach(item => {
          TicketInfo.push(this.ticketList[item]);
          TicketId.push(this.ticketList[item].ID);
        });
        localStorage.setItem('TicketInfo', JSON.stringify(TicketInfo));
        this.$store.commit('SET_TICKETID', TicketId.join(','));
        this.$store.commit('SET_BUYNUM', this.TicketNum);
        if (this.$route.query.SessionID) {
          // 小程序内
          window.location.href = `#/home/${this.$route.params.st}?SessionID=${
            this.$route.query.SessionID
          }&WeixinID=${this.$route.query.WeixinID}&TickID=${TicketId.join(
            ','
          )}&BuyNum=${this.TicketNum}`;
        } else {
          window.location.href = `#/home/${
            this.$route.params.st
          }?TickID=${TicketId.join(',')}&BuyNum=${this.TicketNum}`;
        }
      }
    },
    beforeClose(action, done) {
      if (action === 'confirm') {
        this.ExchangeCoupon();
      }
      if (action === 'cancel') {
        this.unuseCoupon();
      }
      done();
    },
    unuseCoupon() {
      this.couponModelShow = false;
      this.maxCheckedNum = this.ticketList.length;
      this.$store.commit('SET_PROMOCODE', null);
      this.couponTitle = '优惠码兑换';
    },
    ExchangeCoupon() {
      if (this.couponCode == '') {
        this.$toast('请输入要兑换的优惠码');
      } else {
        var that = this;
        $.ajax({
          type: 'POST',
          url: that.baseUrl + '/api/PromoCode/check',
          data: {
            Code: that.couponCode,
            ST: that.$store.state.UserInfo.ST
          },
          success: function(res) {
            if (res.State) {
              that.$toast.success('兑换成功');
              that.couponModelShow = false;
              that.$store.commit('SET_PROMOCODE', that.couponCode);
              that.couponTitle = '已使用优惠码';
              that.maxCheckedNum = 1;
            } else {
              that.$toast.fail('兑换失败');
            }
          }
        });
      }
    },
    ticketCheck() {
      if (this.checkedTicket.length > 0) {
        let arry = [];
        this.checkedTicket.forEach(item => {
          if (this.ticketList[item].SingleBuyNum == 0) {
            arry.push(this.ticketList[item].BuyNum);
          } else {
            arry.push(this.ticketList[item].SingleBuyNum);
          }
        });
        this.maxBuyNum = Math.min.apply(null, arry);
        if (this.TicketNum > this.maxBuyNum) {
          this.TicketNum = this.maxBuyNum;
        }
      }
      this.calcTotalPrice();
    },
    TicketNumChange() {
      this.calcTotalPrice();
    },
    calcTotalPrice() {
      if (this.checkedTicket.length > 0) {
        this.totalPrice = 0;
        this.checkedTicket.forEach(item => {
          this.totalPrice += this.TicketNum * this.ticketList[item].Fee;
        });
      } else {
        this.totalPrice = 0;
      }
    }
  }
};
</script>

